package com.sfj.system.service.jiekou;

import cn.hutool.system.UserInfo;
import com.sfj.system.enums.MockUserEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author kaka
 * @Date 2025/08/25
 */
@Service
@Slf4j
public class TongyiSerrvice {

    @Autowired
    private TongyiProperties tongyiProperties;
    @Value("${spring.profiles.active:}")
    private String activeProfile;

    public TongyiUserInfo login(String code) throws IOException {
        if ("local".equalsIgnoreCase(activeProfile)) {
            MockUserEnum mock = MockUserEnum.fromCode(code);
            TongyiUserInfo mockUser = new TongyiUserInfo();
            if (mock != null) {
                mockUser.setUserName(mock.getUserName());
                mockUser.setLoginName(mock.getLoginName());
                return mockUser;
            } else {
                throw new IllegalArgumentException("未知的本地模拟用户 code: " + code);
            }
        } else {
            OAuthClient oAuthClient = new OAuthClient();

            //测试用 到时候替换掉 todo
            //if("7758258".equals(code)){
            //    MockUserEnum mock = MockUserEnum.fromCode(code);
            //    TongyiUserInfo mockUser = new TongyiUserInfo();
            //    if (mock != null) {
            //        mockUser.setUserName(mock.getUserName());
            //        mockUser.setLoginName(mock.getLoginName());
            //        return mockUser;
            //    } else {
            //        throw new IllegalArgumentException("未知的本地模拟用户 code: " + code);
            //    }
            //}

            String accessToken = oAuthClient.getToken(tongyiProperties.getClientId(),
                    tongyiProperties.getClientSecret(), code,
                    tongyiProperties.getRedirectUri());
            log.info("access_token: {}" + accessToken);
            // 获取用户信息
            TongyiUserInfo user = oAuthClient.getUserInfo(accessToken);
            log.info("用户信息: {}" + user);
            return user;
        }
    }
}
